package com.wdb.modules.security.service;

import com.wdb.modules.security.config.bean.SecurityProperties;
import com.wdb.modules.security.security.TokenProvider;
import com.wdb.modules.security.service.dto.JwtUserDto;
import com.wdb.modules.security.service.dto.OnlineUserDto;
import com.wdb.utils.EncryptUtils;
import com.wdb.utils.RedisUtils;
import com.wdb.utils.StringUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author: wendaobai@qq.com
 * @date: 2024/1/10 0010 16:16
 */
@Service
@Slf4j
@AllArgsConstructor
public class OnlineUserService {
  private final SecurityProperties properties;
  private final RedisUtils redisUtils;
  private final TokenProvider tokenProvider;
  /**
   * 根据用户名强退用户
   *
   * @param username /
   */
  @Async
  public void kickOutForUsername(String username) {
    String loginKey = properties.getOnlineKey() + username + "*";
    redisUtils.scanDel(loginKey);
  }

  /**
   * 保存在线用户信息
   *
   * @param jwtUserDto /
   * @param token /
   * @param request /
   */
  public void save(JwtUserDto jwtUserDto, String token, HttpServletRequest request) {
    String dept = jwtUserDto.getUser().getDept().getName();
    String ip = StringUtils.getIp(request);
    String browser = StringUtils.getBrowser(request);
    String address = StringUtils.getCityInfo(ip);
    OnlineUserDto onlineUserDto = null;
    try {
      onlineUserDto =
          new OnlineUserDto(
              jwtUserDto.getUsername(),
              jwtUserDto.getUser().getNickName(),
              dept,
              browser,
              ip,
              address,
              EncryptUtils.desEncrypt(token),
              new Date());
    } catch (Exception e) {
      log.error(e.getMessage(), e);
    }
    String loginKey = tokenProvider.loginKey(token);
    redisUtils.set(
        loginKey, onlineUserDto, properties.getTokenValidityInSeconds(), TimeUnit.MILLISECONDS);
  }
  /**
   * 查询用户
   *
   * @param key /
   * @return /
   */
  public OnlineUserDto getOne(String key) {
    return (OnlineUserDto) redisUtils.get(key);
  }
}
